using System;
using System.Linq;

namespace Dorm.Maps
{
    public class MappedProperty
    {
        public string PropertyName { get; set; }
        public Type PropertyType { get; set; }
        public MappingTypes MappingType { get; set; }
        public bool Cascade { get; set; }
        public int Length { get; set; }

        public static string GetManyToManyTableName(string oneType, string otherType)
        {
            string[] tableNames = new string[] { oneType, otherType }.OrderBy(s => s).ToArray();
            return tableNames[0] + tableNames[1];
        }

        public string GetDbTypeName()
        {
            switch (PropertyType.Name)
            {
                case "String": Length = 200; return "varchar";
                case "Decimal": Length = 20; return "decimal";
                case "Double": Length = 20; return "decimal";
                case "Boolean": return "bit";
                case "Int16": return "tinyint";
                case "Int32": return "int";
                case "Int64": return "bigint";
                case "DateTime": return "smalldatetime";
                case "TimeSpan": return "smalldatetime";
                default:
                    if (PropertyType.IsEnum)
                        return "int";
                    else if (PropertyType.GetProperty("ID") != null)
                        return "bigint";
                    Length = 200; return "varchar";
            }
        }

        public enum MappingTypes { Simple, Reference, HasMany, HasManyToMany, Component }

        internal bool IsFirstOnManyToMany(string thisTable)
        {
            string otherTable = this.PropertyType.Name;
            string manyToManyTableName = GetManyToManyTableName(thisTable, otherTable);
            return manyToManyTableName.StartsWith(thisTable);
        }

        public override string ToString()
        {
            return PropertyType + " " + PropertyName + " (" + MappingType + ")";
        }
    }
}